// pages/profile/friendInfo/index.ts
import tran from "../../utils/language";
import {
    contactFriend,
    contactBlacklist,
    deleteContactFriend,
    userTargetInfo,
    profilePhone,
    friendRequestPopUp,
} from "../../utils/api.js";
Component({
    /**
     * 组件的属性列表
     */
    properties: {
        homeFriendInfo: {
            type: Object,
            value: {
                userId: "",
                homeFriendInfoFlag: "",
                friendStatus: 0,
                jumpType: "",
                requestPlayIds: "",
                requestHelpIds: "",
                requestTalkIds: "",
                avatarurl: "",
                nickname: "",
                personalityAvatar: "",
                friendSourceInfo: {
                    friendStatus: 1,
                },
            },
            observer(newVal) {
                if (newVal && Object.keys(newVal).length > 0) {
                    newVal.friendStatus = newVal.friendSourceInfo.friendStatus;
                    newVal.avatarurl = newVal.avatarurl || newVal.avatar;
                    newVal.nickname = newVal.nickname || newVal.pushName;
                    this.handleUserInfo(newVal);
                    // this.getFriendAddMsg();
                }
            },
        },
    },
    // getFriendRequestPopUp
    /**
     * 组件的初始数据
     */
    data: {
        _t: tran._t("homeFriendInfo"),
        _tBase: tran._t("base"),
        indicatorDots: false,
        vertical: false,
        autoplay: false,
        interval: 2000,
        duration: 500,
        showEventPopup: false,
        imgList: [
            {
                img: "https://res.wx.qq.com/wxdoc/dist/assets/img/0.4cb08bb4.jpg",
                selectFlag: true,
            },
        ],
        selectBtnList: [
            {
                selectFlag: true,
                text: "烹饪",
            },
        ],
        skillList: [
            {
                selectFlag: true,
                text: "数据分析",
                img: "/images/expert.png",
            },
        ],
        langList: [
            {
                selectFlag: true,
                text: "英语",
            },
        ],
        personalityData: [
            {
                title: "Lorem ipsum",
                remark: "Sed ut perspiciatis unde omnis iste natuserror sit voluptatem accusantiumi doloremque laudantium, totam remquae ab illo inventoreaperiam, eaque ipsa570rpXbeatae vitaeveritatis et quasi aridicta sunt explicaboNemo enim ipsam voluptatem quia voluptassit aspernatur aut odit aut fugit, sed quiaconsequuntur magni dolores eos quiratio",
            },
            {
                title: "Lorem ipsum",
                remark: "Sed ut perspiciatis unde omnis iste natuserror sit voluptatem accusantiumi doloremque laudantium, totam remquae ab illo inventoreaperiam, eaque ipsa570rpXbeatae vitaeveritatis et quasi aridicta sunt explicaboNemo enim ipsam voluptatem quia voluptassit aspernatur aut odit aut fugit, sed quiaconsequuntur magni dolores eos quiratio",
            },
            {
                title: "Lorem ipsum",
                remark: "Sed ut perspiciatis unde omnis iste natuserror sit voluptatem accusantiumi doloremque laudantium, totam remquae ab illo inventoreaperiam, eaque ipsa570rpXbeatae vitaeveritatis et quasi aridicta sunt explicaboNemo enim ipsam voluptatem quia voluptassit aspernatur aut odit aut fugit, sed quiaconsequuntur magni dolores eos quiratio",
            },
        ],
        popupParams: {
            showPopup: false,
            showType: 0, // 0更新个人资料  1发送好友请求
        },
        skillPopupParams: {
            showPopup: false,
        },
        sendFlag: true,
        hasSendFlag: true,
        userInfo: {
            interests: [],
            skills: [],
            userId: "",
        },
        interestList: [],
        professionList: [],
        loginInfo: {
            interestIds: [],
            skills: [],
            friendRequestPopUp: false,
        },
        levelList: [
            {
                text: tran._t("homeFriendInfo")["basicText"],
                img: "/images/mango1.png",
            },
            {
                text: tran._t("homeFriendInfo")["intermediateText"],
                img: "/images/mango2.png",
            },
            {
                text: tran._t("homeFriendInfo")["advancedText"],
                img: "/images/mango3.png",
            },
            {
                text: tran._t("homeFriendInfo")["expertText"],
                img: "/images/mango4.png",
            },
        ],
        confirmPopup: {
            showPopup: false,
            topTitle: tran._t("base").topTitleTip,
            midText: tran._t("base").blockNameTip,
            confirmText: tran._t("base").confirmText,
            closeText: tran._t("base").closeBtnText,
        },
        isSendFlag: false,
    },

    /**
     * 组件的方法列表
     */
    methods: {
        // 禁止开启好友弹框
        getFriendRequestPopUp() {
            friendRequestPopUp({}).then((res: any) => {
                // 更新个人资料，是否开启弹框
                getApp().getUserInfo();
            });
        },
        confirmFn() {
            const { userInfo } = this.data;
            // 调用 IM 的 API 将用户添加到黑名单
            wx.conn.addUsersToBlocklist({
                //可以添加单个用户 ID 或批量添加多个用户 ID 组成的数组。
                name: [userInfo.userId],
            });
            this.onCloseEventPopup();
            this.closeFn();
            setTimeout(() => {
                this.joinBlack();
            }, 300);
        },
        closeFn() {
            const { confirmPopup } = this.data;
            confirmPopup.showPopup = false;
            this.setData({
                confirmPopup,
            });
        },
        /**
         * 点击解锁个人资料
         */
        openUnlockInfo() {
            this.handleProfilePhone(true);
        },
        // 取消解锁按钮
        closeUnlockInfo() {
            this.handleProfilePhone(false);
        },
        // 解锁/取消解锁个人资料接口调用
        handleProfilePhone(unlock: any) {
            console.log(unlock);
            const { userInfo } = this.data;
            const params = {
                targetUserId: userInfo.userId,
                unlock: unlock, // true解锁  false取消解锁
            };
            profilePhone(params).then((res) => {
                wx.showToast({
                    title: "操作成功",
                });
                this.closeFriend();
                this.setData({ showEventPopup: false });
            });
        },
        tapDot() {
            this.setData({
                showEventPopup: true,
            });
        },
        /**
         * 加入黑名单
         */
        joinBlackName() {
            const { confirmPopup } = this.data;
            confirmPopup.showPopup = true;
            this.setData({
                confirmPopup,
            });
        },
        /**
         * 加入黑名单（我们这边的接口，得先调用im的加入黑名单接口后，再调用此接口）
         */
        joinBlack() {
            const { userInfo } = this.data;
            const params = {
                tagetUserId: userInfo.userId,
                flag: true, // true加入黑名单 false移除黑名单
            };
            contactBlacklist(params).then((res: any) => {
                wx.showToast({
                    title: "操作成功",
                });
                this.closeFriend();
            });
        },
        /**
         * 删除好友
         */
        deleteFriend() {
            const { userInfo } = this.data;
            const that = this;
            this.onClosePopup();
            wx.showModal({
                title: "提示",
                content: "确定要删除该用户？",
                success(res) {
                    if (res.confirm) {
                        // 调用 IM 的 API 删除好友
                        let options = {
                            // 会话 ID：单聊为对方的用户 ID，群聊为群组 ID。
                            channel: userInfo.userId,
                            // 会话类型：（默认） `singleChat`：单聊；`groupChat`：群聊。
                            chatType: "singleChat",
                            // 删除会话时是否同时删除服务端漫游消息。
                            // deleteRoam: true,
                            deleteRoam: true,
                        };
                        wx.conn
                            .deleteConversation(options)
                            .then((res) => {
                                console.log(res);
                            })
                            .catch((e) => {
                                // 删除失败。
                            });
                        wx.conn.deleteContact(userInfo.userId);
                        setTimeout(() => {
                            that.deleteFriendInt(userInfo.userId);
                        }, 500);
                    } else if (res.cancel) {
                        console.log("用户点击取消");
                    }
                },
            });
        },
        /**
         * 删除好友（先调用IM删除好友接口，再调此接口）
         */
        deleteFriendInt(targetUserId: string) {
            const params = {
                targetUserId: targetUserId,
            };
            deleteContactFriend(params).then((res: any) => {
                // this.getList()
                this.closeFriend("del");
            });
        },
        onCloseEventPopup() {
            // const customPopup = this.selectComponent('#event-popup');
            // customPopup && customPopup.hidePopup()
            this.setData({
                showEventPopup: false,
            });
        },
        getFriendAddMsg() {
            wx.conn.addEventHandler("contactEvent", {
                // 当前用户收到好友请求。用户 B 向用户 A 发送好友请求，用户 A 收到该事件。
                onContactInvited: function (msg: any) {
                    console.log(msg, 1111);
                },
                // 当前用户被其他用户从联系人列表上移除。用户 B 将用户 A 从联系人列表上删除，用户 A 收到该事件。
                onContactDeleted: function (msg: any) {
                    console.log(msg, 2222);
                },
                // 当前用户新增了联系人。用户 B 向用户 A 发送好友请求，用户 A 同意该请求，用户 A 收到该事件，而用户 B 收到 `onContactAgreed` 事件。
                onContactAdded: function (msg: any) {
                    console.log(msg, 333);
                },
                // 当前用户发送的好友请求被拒绝。用户 A 向用户 B 发送好友请求，用户 B 收到好友请求后，拒绝加好友，则用户 A 收到该事件。
                onContactRefuse: function (msg: any) {
                    console.log(msg, 444);
                },
                // 当前用户发送的好友请求经过了对方同意。用户 A 向用户 B 发送好友请求，用户 B 收到好友请求后，同意加好友，则用户 A 收到该事件。
                onContactAgreed: function (msg: any) {
                    console.log(msg, 555);
                },
            });
            wx.conn.getRoster({
                success: function (roster: any) {
                    console.log("好友列表:", roster);
                    // 处理好友列表，筛选出待添加的好友请求
                },
                error: function (e: any) {
                    console.error("获取好友列表失败:", e);
                },
            });
        },

        /**
         * 获取IM是否登录
         */
        async getImData() {
            const { userInfo } = this.data;
            const that = this;
            let wxIm = wx.conn;
            // 判断是否IM连接成功
            if (wxIm) {
                wx.conn.addContact(userInfo.userId, "添加好友");
                // 此处表示已查到im,就停止
                return;
            } else {
                // 如果没有wx.im，说明im还没连接成功，就再次调用getImData方法继续查
                setTimeout(() => {
                    that.getImData();
                }, 500);
            }
        },
        closeFriend(type?: string) {
            this.triggerEvent("onClose", type);
        },
        /**
         * 点击发送请求按钮
         */
        addFriendTap() {
            const { userInfo, popupParams, homeFriendInfo, sendFlag } =
                this.data;
            // 调用im接口后，在调用我们这边服务的接口
            // wx.conn.addContact(userInfo.userId, '添加好友')
            // 调用方法，然后调用添加好友
            this.getImData();
            let friendSource = "NONE";
            let friendSourceTagTypeId = "";
            if (homeFriendInfo.jumpType == "1") {
                // 找搭子
                friendSource = "INTEREST";
                friendSourceTagTypeId = homeFriendInfo.requestPlayIds || "";
            } else if (homeFriendInfo.jumpType == "2") {
                // 找师傅
                friendSource = "SKILL";
                friendSourceTagTypeId = homeFriendInfo.requestHelpIds || "";
            } else if (homeFriendInfo.jumpType == "3") {
                // 找朋友
                friendSource = "TOPIC ";
                friendSourceTagTypeId = homeFriendInfo.requestTalkIds || "";
            } else {
                // 普通进来的
                friendSource = "NONE";
            }
            const params = {
                tagetUserId: userInfo.userId, // 目标用户ID
                friendSource: friendSource, // 添加好友时的来源 NONE：无, INTEREST：兴趣, SKILL：技能, TOPIC：主题
                optionType: "ADD", // 操作类型  ADD：添加, AGREED：同意, REFUSE：拒绝
                friendSourceTagTypeId: friendSourceTagTypeId, // 添加好友时好友来源关联的标签类型ID
            };
            contactFriend(params).then((res: any) => {
                console.log(res);
                wx.showToast({
                    title: "操作成功",
                });
            });
            // 判断如果是true，就是禁止开启弹框
            if (sendFlag) {
                // 调用此接口就是禁止开启弹框，否则就不调用
                this.getFriendRequestPopUp();
            }
            homeFriendInfo.friendSourceInfo.friendStatus = 2;
            popupParams.showPopup = false;
            this.setData({
                popupParams,
                isSendFlag: true,
                homeFriendInfo,
            });
        },
        goChat(e: any) {
            const { homeFriendInfo } = this.data;
            this.closeFriend("close");
        },
        /**
         * 获取登录的用户的详情
         */
        getLoginInfo() {
            const loginInfo = wx.getStorageSync("userInfo");
            this.setData({
                loginInfo,
            });
        },
        /**
         * 处理用户的兴趣与技能
         */
        getprofessionAndInterest() {
            const { userInfo, loginInfo } = this.data;
            // 获取当前登录的兴趣和技能
            const logininterests = loginInfo.interestIds;
            const loginSkills = loginInfo.skills;
            // 获取用户的兴趣和技能
            const { interests, skills } = userInfo;
            interests.length > 0 &&
                interests.map((item: any) => {
                    const list = logininterests.filter(
                        (item1: any) => item1 == item.tagTypeId
                    );
                    if (list.length > 0) {
                        item.selectFlag = true;
                    }
                });
            skills.length > 0 &&
                skills.map((item: any) => {
                    item.img = "/images/expert.png";
                    const list = loginSkills.filter(
                        (item1: any) => item1.tagTypeId == item.tagTypeId
                    );
                    if (list.length > 0) {
                        item.selectFlag = true;
                    }
                    if (item.skillProficiency == "BASIC") {
                        // 基础
                        item.img = "/images/mango1.png";
                    } else if (item.skillProficiency == "INTERMEDIATE") {
                        item.img = "/images/mango2.png";
                    } else if (item.skillProficiency == "ADVANCED") {
                        item.img = "/images/mango3.png";
                    } else {
                        // 专家
                        item.img = "/images/mango4.png";
                    }
                });
            this.setData({
                interestList: interests,
                professionList: skills,
            });
        },
        handleUserInfo(info: any) {
            let imgList: any = [];
            const { photos, languages } = info;
            // homeFriendInfo.friendStatus = homeFriendInfo.friendSourceInfo.friendStatus
            photos &&
                photos.length > 0 &&
                photos.map((item: any, index: Number) => {
                    // if (index == 0) {
                    //   item.selectFlag = true
                    // }else {
                    //   item.selectFlag = false
                    // }
                    const obj = {
                        img: item,
                        selectFlag: index == 0 ? true : false,
                    };
                    imgList.push(obj);
                });
            let list: any = [];
            languages.length > 0 &&
                languages.map((item: any) => {
                    if (item.language == "zh_CN") {
                        item.text = "普通话";
                    } else if (item.language == "en_US") {
                        item.text = "英语";
                    }
                    list.push(item);
                });
            this.setData(
                {
                    userInfo: info,
                    imgList,
                    langList: list,
                },
                () => {
                    this.getLoginInfo();
                    this.getprofessionAndInterest();
                }
            );
        },
        addFriend() {
            let { popupParams } = this.data;
            popupParams.showPopup = true;
            // popupParams.showType = 1 // 发送好友请求
            popupParams.showType = 0; // 提示更新个人资料
            this.setData({
                popupParams,
            });
        },
        toUpdate() {
            getApp().globalData.profileFrom = "edit";
            wx.navigateTo({
                url: "/pages/profile/create-account/index?type=edit",
            });
        },
        openLevel() {
            const { skillPopupParams } = this.data;
            skillPopupParams.showPopup = true;
            this.setData({
                skillPopupParams,
            });
        },
        closeLevelPopup() {
            const { skillPopupParams } = this.data;
            skillPopupParams.showPopup = false;
            this.setData({
                skillPopupParams,
            });
        },
        closePopup() {
            this.setData({ popupParams: { showPopup: false, showType: 1 } });
        },
        onClosePopup() {
            const customPopup = this.selectComponent("#custom-popup");
            customPopup && customPopup.hidePopup();
        },
        onCloseMidPopup() {
            const { popupParams, loginInfo } = this.data;
            if (loginInfo.friendRequestPopUp) {
                // 为true，就是开启弹框
                popupParams.showType = 1;
                this.setData({
                    popupParams,
                });
            } else {
                // 为false，就不开启弹框，直接发送好友申请
                this.addFriendTap();
            }
        },
        swiperChange(e: any) {
            const currentIndex = e.detail.current;
            const { imgList } = this.data;
            imgList.length > 0 &&
                imgList.map((item, index) => {
                    if (index === currentIndex) {
                        item.selectFlag = true;
                    } else {
                        item.selectFlag = false;
                    }
                });
            this.setData({
                imgList,
            });
        },
        sendChange(e: any) {
            this.setData({
                sendFlag: e.detail,
            });
        },
        changeLangSelect(e: any) {
            const { info } = e.currentTarget.dataset;
            const { langList } = this.data;
            // 判断用户点击的是哪一个按钮，从而将那一个按钮状态反选
            langList.map((item) => {
                if (item.text === info.text) {
                    item.selectFlag = !item.selectFlag;
                }
            });
            this.setData({
                langList: langList,
            });
        },
        changeSkillSelect(e: any) {
            const { info } = e.currentTarget.dataset;
            const { skillList } = this.data;
            // 判断用户点击的是哪一个按钮，从而将那一个按钮状态反选
            skillList.map((item) => {
                if (item.text === info.text) {
                    item.selectFlag = !item.selectFlag;
                }
            });
            this.setData({
                skillList: skillList,
            });
        },
        changeSelect(e: any) {
            const { info } = e.currentTarget.dataset;
            const { selectBtnList } = this.data;
            // 判断用户点击的是哪一个按钮，从而将那一个按钮状态反选
            selectBtnList.map((item) => {
                if (item.text === info.text) {
                    item.selectFlag = !item.selectFlag;
                }
            });
            this.setData({
                selectBtnList: selectBtnList,
            });
        },
        changeIndicatorDots() {
            this.setData({
                indicatorDots: !this.data.indicatorDots,
            });
        },

        changeAutoplay() {
            this.setData({
                autoplay: !this.data.autoplay,
            });
        },

        intervalChange(e: any) {
            this.setData({
                interval: e.detail.value,
            });
        },

        durationChange(e: any) {
            this.setData({
                duration: e.detail.value,
            });
        },
    },
});
